package com.lry.basic.algorithm.flow.bucket;


import java.util.concurrent.atomic.LongAdder;

public class Bucket {

    //桶的容量
    private int capacity;

    //桶的当前水量
    private int water;

    //桶的流出速率,1s 流出rate个
    private int rate;

    public Bucket(int capacity, int rate) {
        this.capacity = capacity;
        this.rate = rate;
        start();
    }

    public synchronized boolean acquire(){
        if(water>=capacity){
            return false;
        }else{
            water++;
            return true;
        }
    }

    private void start(){
        new Thread(()->{
            while(true){
                if(water>0){
                    water--;
                }
                try {
                    Thread.sleep(1000/rate);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
